package com.qf.service.impl;

import com.qf.dao.AccountDao;
import com.qf.pojo.Account;
import com.qf.service.AccountService;
import com.qf.utils.TransactionManager;

/**
 * @Description: 公用常量
 * @Data: 2022/9/1 8:38
 * @Pacakge: com.qf.service.impl
 * @ClassName: AccountServiceImpl
 * @Author: fan
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private TransactionManager transactionManager;
    /**
     * 转账操作
     * @param sourceName 转出账户名称
     * @param targetName 转入账户名称
     * @param money 转账金额
     */
    @Override
    public void transfer(String sourceName, String targetName, Double money) {


        try {
            //开启事务
            transactionManager.beginTransaction();
            //根据名称查询出转账用户
            Account sourceAccount = accountDao.findAccountByName(sourceName);
            //根据名称查询转入账用户
            Account targetAccount = accountDao.findAccountByName(targetName);
            //转出账户扣钱
            sourceAccount.setMoney(sourceAccount.getMoney() - money);
            //转入账户加钱
            targetAccount.setMoney(targetAccount.getMoney() + money);
            //更新转出账户
            accountDao.updateAccount(sourceAccount);
            //int i = 1/0;
            //更新转入账户
            accountDao.updateAccount(targetAccount);
            //提交事务
            transactionManager.commitTransaction();
        } catch (Exception e) {
            //事务回滚
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }finally{
            //释放资源
            transactionManager.release();
        }
    }
}
